﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Kaio.Core;
using Kaio.Core.Extension;
using Kaio.Web.UI.Attributes;
using MvcForum.Net.Bussiness;

namespace MvcForum.Net.Controllers
{
    [ValidateIpAddress]
    [HandleError(View = "Error")]
    public class MemberController : BaseController
    {
        //
        // GET: /Member/


        public List<ForumUrl> Address
        {
            get
            {

                return new List<ForumUrl>
                           {
                               new ForumUrl
                                   {
                                       Title = ForumContext.GetText(LanguageSection.MEMBER,"PAGE_NAME")
                                   }
                           };
            }
        }

        [RequiredAuthentication]
        public ActionResult List()
        {

            int _pageIndex;

            int.TryParse(Request.QueryString["P"], out _pageIndex);
            if (_pageIndex <= 0)
                _pageIndex = 1;

            int _totalRows;

            int _pageSize = ForumContext.Configuration.PageSize;

            var _data = UsersRepo.List("", "", "", _pageIndex, _pageSize, out _totalRows);

            ViewBag.PageRender = ForumContext.PageRender(ForumContext.GetAbsoluteUrl(ForumUrls.MEMBERS) + "?P={0}", _pageIndex, _pageSize, _totalRows);

            var _add = Address;

            var _url = new ForumUrl
                           {
                               Title = ForumContext.GetText(LanguageSection.MEMBER, "MEMBER_LIST"),
                               Url = ForumContext.GetAbsoluteUrl(ForumUrls.MEMBERS)
                           };

            _add.Add(_url);



            ViewBag.ActiveUrl = _url;
            ViewBag.NavAddress = _add;


            return View(_data);
        }

        public ActionResult WhoIsOnline()
        {


            var _add = Address;

            var _url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.WHO_IS_ONLINE, "PAGE_NAME"),
                Url = ForumContext.GetAbsoluteUrl(ForumUrls.WHO_IS_ONLINE)
            };

            _add.Add(_url);

            ViewBag.ActiveUrl = _url;
            ViewBag.NavAddress = _add;

            int _pageIndex;

            int.TryParse(Request.QueryString["P"], out _pageIndex);
            if (_pageIndex <= 0)
                _pageIndex = 1;

            int _totalRows;

             int _pageSize = ForumContext.Configuration.PageSize;

            var _data = ActivityRepo.List("", "", "", _pageIndex, _pageSize, out _totalRows);

            ViewBag.PageRender = ForumContext.PageRender(ForumContext.GetAbsoluteUrl(ForumUrls.WHO_IS_ONLINE) + "?P={0}", _pageIndex, _pageSize, _totalRows);


            return View(_data);
        }



        public ActionResult Info(string id)
        {

            int _userId;

            int.TryParse(id, out _userId);

            var _userInfo = _userId > 0 ? UsersRepo.UserInfo(_userId) : UsersRepo.UserInfo(id);


            var _url = new ForumUrl
                           {
                               Title = _userInfo.UserName
                           };


            var _add = Address;
            _add.Add(_url);

            ViewBag.ActiveUrl = _url;
            ViewBag.NavAddress = _add;


            return View(_userInfo);
        }


        #region ActiveRequest

        public ActionResult ActiveRequest()
        {

            var _title = ForumContext.GetText(LanguageSection.ACTIVE_REQUEST, "PAGE_NAME");

            ViewBag.ActiveUrl = new ForumUrl { Title = _title, Url = ForumContext.GetAbsoluteUrl(ForumUrls.ACTIVE_REQUEST) };


            return View();
        }


        [HttpPost]
        [ValidatePostback]
        [ReCaptchaValidation]
        public ActionResult ActiveRequest(FormCollection form)
        {
            var _msg = Msg.Create();

            if (Convert.ToBoolean(RouteData.Values["captchaValid"]))
            {

                bool _valid = true;

                string _email = form["email"];

                if (!_email.EmailIsValid())
                {
                    _msg.Text = _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.EmailInvalid.ToString()); ;
                    _valid = false;
                }
                else if (!UsersRepo.EmailExists(_email))
                {
                    _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.EmailNotExists.ToString());
                    _valid = false;
                }


                if (_valid)
                {
                    string _subject = ForumContext.GetText(LanguageSection.ACTIVE_REQUEST, "EMAIL_SUBJECT");

                    string _activeCode = Guid.NewGuid().ToString();

                    string _activeLink = ForumContext.GetAbsoluteUrl(ForumUrls.ACTIVE_ACCOUNT) + string.Format("?email={0}&a={1}", _email, _activeCode);

                    string _message = string.Format(ForumContext.GetText(LanguageSection.ACTIVE_REQUEST, "EMAIL_BODY"), _email, _activeLink);

                    RequestRepo.Save(_email, _activeCode, (int)RequestType.Actived);

                    EmailQueueRepo.Save(ForumContext.Configuration.SmtpSender, _email, _subject, _message, EmailPriority.Hight);


                    _msg.ReturnUrl = ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.RequestActiveSuccess);


                }

            }
            else
            {

                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.CaptchaInvalid);
            }



            return JavaScript(_msg.ToJavaScript());

        }


        #endregion





        #region Login & Logout

        public ActionResult Logout()
        {
            ForumContext.SignOut();

            if (Request.IsAjaxRequest())
            {
                return JavaScript("window.location.reload();");
            }

            return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.HOME_PAGE));
        }

        public ActionResult Login()
        {

            /* var _returnUrl= !string.IsNullOrWhiteSpace(Request.QueryString["ReturnUrl"])
                                   ? Request.QueryString["ReturnUrl"]
                                   : Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "/";*/


            if (ForumContext.Logined)
            {
                return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.HOME_PAGE));
            }

            ViewBag.ReturnUrl = ForumContext.ReturnUrl;

            if (Request.IsAjaxRequest() || Request.QueryString["ajax"] == "1")
            {
                return PartialView("_LoginForm");
            }

            var _title = ForumContext.GetText(LanguageSection.LOGIN, "PAGE_NAME");
            var _url = new ForumUrl { Title = _title, Url = ForumContext.GetAbsoluteUrl(ForumUrls.LOGIN) };
            ViewBag.ActiveUrl = _url;

            ViewBag.NavAddress = new List<ForumUrl> { _url };

            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidatePostback]
        public ActionResult Login(FormCollection form)
        {
            string _username = form["_user"];
            string _pwd = form["_pwd"].Password();
            bool _autoLogin = form["_auto"].IsBoolean();

            var _msg = Msg.Create();

            UserInfo _user = UsersRepo.LogIn(_username, _pwd, true);

            if (_user != null)
            {
                if (!_user.IsActived && ForumContext.Configuration.RegisterEmailActiveRequired)
                {
                    _msg.Text = String.Format(ForumContext.GetText(LanguageSection.MESSAGES, Messages.AccountNoActive.ToString()),
                                         ForumContext.GetAbsoluteUrl(ForumUrls.ACTIVE_REQUEST));
                }
                else
                {
                    var _returnUrl = form["returnUrl"];

                    ForumContext.SetAuthenticationCookie(_username, _pwd, _autoLogin);
                    _msg.ReturnUrl = _returnUrl;
                    if (string.IsNullOrWhiteSpace(_returnUrl))
                    {
                        _msg.Reload = true;
                    }

                }
            }
            else
            {
                _msg.Text = String.Format(ForumContext.GetText(LanguageSection.MESSAGES, Messages.UserNameOrPwdInvalid.ToString()), ForumContext.GetAbsoluteUrl(ForumUrls.LOST_PWD));
            }

            return JavaScript(_msg.ToJavaScript());
        }


        #endregion


        #region Register

        public ActionResult Register()
        {

            if (ForumContext.Logined)
            {
                return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.HOME_PAGE));
            }

            var _title = ForumContext.GetText(LanguageSection.REGISTER, "PAGE_NAME");

            var _url = new ForumUrl { Title = _title, Url = ForumContext.GetAbsoluteUrl(ForumUrls.REGISTER) };

            ViewBag.ActiveUrl = _url;

            ViewBag.NavAddress = new List<ForumUrl> { _url };

            ViewBag.ReturnUrl = ForumContext.ReturnUrl;


            if(Request.QueryString["agree"]=="1")
            {
                return View();    
            }
            return View("_RuleBox");
        }




        [HttpPost]
        [ValidateAntiForgeryToken]
        [ReCaptchaValidation]
        public ActionResult Register(FormCollection form)
        {


            bool _valid = true;
            var _msg = Msg.Create();
            _msg.Alert = true;
            if (Convert.ToBoolean(RouteData.Values["captchaValid"]))
            {

                string userName = form["username"];

                string pwd = form["pwd"].Password();

                string email = form["email"];

                double timezone =  TimeSpan.Parse(form["timezone"]).TotalDays;

                string activeCode = "";
                //string _returnUrl = form.GetValue<string>("returnUrl");


                if (userName.NameIsDisallowed())
                {
                    _msg.Text = string.Format(ForumContext.GetText(LanguageSection.REGISTER, "NAME_IS_DISALLOWED"),
                                              userName);
                    _valid = false;
                }
                else if (!email.IsEmail())
                {
                    _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.EmailInvalid.ToString());

                    _valid = false;
                }

                else if (!email.IsEmail())
                {
                    _msg.Text = string.Format(ForumContext.GetText(LanguageSection.REGISTER, "EMAIL_NOT_ALLOW"), email);
                    _valid = false;
                }
                else if (UsersRepo.UserNameExists(userName))
                {
                    _msg.Text = string.Format(ForumContext.GetText(LanguageSection.REGISTER, "USERNAME_EXISTS"),
                                              userName, ForumContext.GetAbsoluteUrl(ForumUrls.LOGIN), ForumContext.GetAbsoluteUrl(ForumUrls.LOST_PWD));
                    _valid = false;
                }
                else if (UsersRepo.EmailExists(email))
                {
                    _msg.Text = string.Format(ForumContext.GetText(LanguageSection.REGISTER, "EMAIL_EXISTS"), email, ForumContext.GetAbsoluteUrl(ForumUrls.LOGIN), ForumContext.GetAbsoluteUrl(ForumUrls.LOST_PWD));
                    _valid = false;
                }

                string _activeLink = null;

                if (_valid)
                {
                    string _emailSubject;
                    if (ForumContext.Configuration.RegisterEmailActiveRequired)
                    {
                        activeCode = Guid.NewGuid().ToString();
                        _msg.ReturnUrl = ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.RegisterSuccess);


                        _emailSubject = ForumContext.GetText(LanguageSection.REGISTER, "ACTIVE_ACCOUNT");

                        _activeLink = ForumContext.GetAbsoluteUrl(ForumUrls.ACTIVE_ACCOUNT) + "?email=" + email + "&a=" + activeCode;
                    }
                    else
                    {
                        _emailSubject = ForumContext.GetText(LanguageSection.REGISTER, "REG_SUCCESS");

                        ForumContext.SetAuthenticationCookie(userName, pwd, false);

                        _msg.ReturnUrl = form.GetValue<string>("returnUrl");
                    }



                    string _emailBody = string.Format(ForumContext.GetText(LanguageSection.REGISTER, "EMAIL_BODY"),
                                                      userName,
                                                      ForumContext.Configuration.ForumName);

                    if (!string.IsNullOrEmpty(_activeLink))
                    {
                        _emailBody += string.Format(ForumContext.GetText(LanguageSection.REGISTER, "ACTIVE_INFO"),
                                                    _activeLink,
                                                    _activeLink);
                        // _emailBody += _activeLink;
                    }

                    //
                    UsersRepo.Register(userName, pwd, email, timezone);

                    // Save Request
                    RequestRepo.Save(email, activeCode, (int)RequestType.Actived);

                    EmailQueueRepo.Save(new Email
                                            {
                                                From = ForumContext.Configuration.SmtpSender,
                                                To = email,
                                                Subject = _emailSubject,
                                                Body = _emailBody,
                                                Priority = (short)EmailPriority.Hight
                                            });

                }


            }
            else
            {

                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.CaptchaInvalid);
            }

            
            return JavaScript(_msg.ToJavaScript());
        }

        #endregion



        #region ResetPwd and LostPwd

        public ActionResult ResetPwd()
        {
            string _a = Request.QueryString["a"];
            string _email = Request.QueryString["email"];
            if (!string.IsNullOrEmpty(_a) && !string.IsNullOrEmpty(_email))
            {
                User _u = UsersRepo.UserInfo(_a, _email);
                if (_u != null)
                {
                    string _newPwd = Utils.RandomNumber(8);

                    string _encrypPwd = Hash.Password(_newPwd, 2);

                    // Update New Pwd
                    UsersRepo.ResetPwd(_u.UserId, _encrypPwd);

                    string _changePwdLink = ForumContext.GetAbsoluteUrl(ForumUrls.CHANGE_EMAIL_PASSWORD);

                    string _subject = ForumContext.GetText(LanguageSection.LOST_PWD, "SUCCESS_SUBJECT");

                    string _message = string.Format(ForumContext.GetText(LanguageSection.LOST_PWD, "SUCCESS_MESSAGE"), _u.UserName, _newPwd, _changePwdLink);


                    // Send Mail new Pwd
                    //ForumContext.SendMail(ForumContext.Configuration.ForumEmail, _email, _subject, _message);

                    EmailQueueRepo.Save(new Email { From = ForumContext.Configuration.SmtpSender, To = _email, Subject = _subject, Body = _message, Priority = (short)EmailPriority.Hight });

                    ForumContext.SignOut();
                    // Auto Login With New Pwd
                    ForumContext.SetAuthenticationCookie(_u.UserName, _encrypPwd, false);

                    return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.HOME_PAGE));
                }
            }


            return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.ActiveCodeInvalid));
        }



        public ActionResult LostPwd()
        {

            var _title = ForumContext.GetText(LanguageSection.LOST_PWD, "PAGE_NAME");

            ViewBag.ActiveUrl = new ForumUrl { Title = _title, Url = ForumContext.GetAbsoluteUrl(ForumUrls.LOST_PWD) };

            return View();
        }

        [HttpPost]
        [ValidatePostback]
        [ReCaptchaValidation]
        public ActionResult LostPwd(FormCollection form)
        {
            var _msg = Msg.Create();

            if (Convert.ToBoolean(RouteData.Values["captchaValid"]))
            {

                bool _valid = true;

                string _email = form["email"];

                if (!_email.IsEmail())
                {
                    _msg.Text = _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.EmailInvalid.ToString()); 
                    _valid = false;
                }
                else if (!UsersRepo.EmailExists(_email))
                {
                    _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.EmailNotExists.ToString());
                    _valid = false;
                }


                if (_valid)
                {
                    string _subject = ForumContext.GetText(LanguageSection.LOST_PWD, "REQUEST_SUBJECT");

                    string _activeCode = Guid.NewGuid().ToString();

                    string _activeLink = ForumContext.GetAbsoluteUrl(ForumUrls.RESET_PWD) + string.Format("?email={0}&a={1}", _email, _activeCode);

                    string _message = string.Format(ForumContext.GetText(LanguageSection.LOST_PWD, "REQUEST_MESSAGE"), _email, ForumContext.Configuration.ForumName, _activeLink);

                    RequestRepo.Save(_email, _activeCode, (int)RequestType.ChangePassword);

                    EmailQueueRepo.Save(ForumContext.Configuration.SmtpSender, _email, _subject, _message, EmailPriority.Hight);


                    _msg.ReturnUrl = ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.ResetPwdSendedSuccess);//RESETPWDSENDEDSUCCESS


                }

            }
            else
            {

                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.CaptchaInvalid);
            }


            return JavaScript(_msg.ToJavaScript());
        }

        #endregion

        public ActionResult Friends()
        {


            if (Request.IsAjaxRequest())
                return PartialView("Friends");

            return View();
        }
    }
}
